import React, { Component } from 'react'
import { EditorState, convertToRaw,ContentState } from 'draft-js'
import { Editor } from "react-draft-wysiwyg"; // what you see is what you get

import draftToHtml from 'draftjs-to-html'
import htmlToDraft from 'html-to-draftjs'


import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

// 富文本编辑器组件
// https://www.npmjs.com/package/react-draft-wysiwyg
export default class RichTextEditor extends Component {
    // constructor(props) {
    //     super(props);
    //     this.state = {
    //         editorState: EditorState.createEmpty(),
    //     };
    // }
    constructor(props) {
        super(props);
        const html = '<p>Hey this <strong>editor</strong> rocks 😀</p>';
        const contentBlock = htmlToDraft(html);
        if (contentBlock) {
            const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
            const editorState = EditorState.createWithContent(contentState);
            this.state = {
                editorState,
            };
        } else {
            this.state = {
                editorState: EditorState.createEmpty(),
            };
        }
    }

    getDetail = () => {
        // 返回输入数据对应的html格式的文本
        return draftToHtml(convertToRaw(this.state.editorState.getCurrentContent()))
    }

    uploadImageCallBack = (file) => {
        return new Promise(
          (resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.open('POST', '/manage/img/upload');
            //xhr.setRequestHeader('Authorization', 'Client-ID XXXXX');
            const data = new FormData();
            data.append('image', file);
            xhr.send(data);
            xhr.addEventListener('load', () => {
              const response = JSON.parse(xhr.responseText);
              const url = response.data.url;    // 得到图片的url
              console.log(url);
              resolve({
                  data:{link:url}
              });
            });
            xhr.addEventListener('error', () => {
              const error = JSON.parse(xhr.responseText);
              reject(error);
            });
          }
        );
      }

    onEditorStateChange = (editorState) => {
        this.setState({
            editorState,
        });
    };

    render() {
        const { editorState } = this.state;
        return (
            <Editor
                editorState={editorState}
                editorStyle={{ border: '1px solid #F1F1F1', minHeight: 200, paddingLeft: 10 }}
                onEditorStateChange={this.onEditorStateChange}
                toolbar={{
                    image: { uploadCallback: this.uploadImageCallBack, alt: { present: true, mandatory: true } },
                }}
            />
        )
    }
}